package com.ljf.tijian.Utils;


import cn.hutool.captcha.generator.RandomGenerator;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.ljf.tijian.pojo.Sms.SmsModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
public class SmsUtils {

    @Autowired
    SmsModel smsModel;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 生成短信验证码
     */
    public String generateSms(String phone){
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsModel.getAccountId();
        String accountToken = smsModel.getAuthToken();
        //请使用管理控制台中已创建应用的APPID
        String appId = smsModel.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId= "1";
        //生成4位随机数
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        String randomNum = randomGenerator.generate();
        Long expire = 2l;
        String []datas = {randomNum,expire.toString()};
        HashMap<String,Object> map = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(map.get("statusCode"))){
            //存入Redis设置有效期
            redisTemplate.opsForValue().set(phone,randomNum);
            redisTemplate.expire(phone,70L, TimeUnit.MINUTES);
            return randomNum;
        }else {
            return null;
        }
    }

    /**
     * 校验短信验证码
     */
    public boolean validateSms(String phone,String sms){
        //取出验证码
        Object obj = redisTemplate.opsForValue().get(phone);
        if(Objects.isNull(obj)){
            throw new RuntimeException("验证码已过期");
        }
        String sms_redis = (String) obj;

        return sms_redis.equals(sms);
    }
}
